
const app = getApp()
Page({
  data: {
    //车牌
    carTxt: '',
    carArray: [],
    carRowId: [],
    carIndex: '',
    initDataCar: [],// 初始化数据只有车辆名称
    sijiCarList: [],// 初始化数据,内可包含强制绑定司机信息
    selectDataCar: '',
    // 司机
    driver: '',
    driverArray: [],
    driverRowId: [],
    driverIndex: '',
    initDatadriver: [],
    selectDatadriver: '',
    // 经纬度
    location: [],
    locationName: '',
    // 图片
    imageUrl: '../../image/repairImg/photograph.png',
    showImage: '',
    autographImage: '',//签名图片
    // canvas相关参数
    ctx: {},
    canvas: [],
    canvasStyle: '',
    // 自定义picker
    showPickerIsok: true,
    code: '',
    placeholder: '',
    baoxiuxiangmu: ""
  },

  onShow () {
    // 存储司机
    this.onLoadGetdataSiji();
    // 存储车辆 如果缓存数据中没有则自己获取数据
    this.onLoadGetdataCar();
  },
  initData () {
    this.setData({
      // 车牌
      carTxt: '',
      carIndex: '',
      selectDataCar: '',
      // 司机
      driver: '',
      driverIndex: '',
      selectDatadriver: '',
      // 图片
      showImage: '',
      autographImage: '',//签名图片
      // canvas相关参数
      ctx: {},
      canvas: [],
      // 自定义picker
      showPickerIsok: true,
      code: '',
      placeholder: '',
      baoxiuxiangmu: ''
    })
  },
  async onLoadGetdataSiji () {
    wx.showLoading()
    let postData = { "table_id": 'e_sijiziliaobiao', "oby": `[e_sijiziliaobiao].row_id` };
    let dataSiji = await wx.$post(3, 'DynamicQuery/query_dynamic_v3', postData);
    wx.hideLoading()
    if (dataSiji.response.errcode != 0) return wx.$toast(res.response.errmsg)
    if (dataSiji.data.row.length > 0) {
      let dataSijiList = dataSiji.data.row;
      let driverArray = [], driverRowId = [];
      for (let value of dataSijiList) {
        driverArray.push(value.jiashiyuanxingming);
        driverRowId.push(value.row_id);
      };
      this.setData({ driverArray, driverRowId, initDatadriver: driverArray })
    } else {
      wx.$toast('司机数据为空!')
    }
  },
  async onLoadGetdataCar () {
    wx.showLoading()
    let postData = { "table_id": 'e_cheliangziliaobiao', "oby": `[e_cheliangziliaobiao].row_id` }
    let dataCheliang = await wx.$post(3, 'DynamicQuery/query_dynamic_v3', postData);
    wx.hideLoading()
    if (dataCheliang.response.errcode != 0) return wx.$toast(res.response.errmsg)
    if (dataCheliang.data.row.length > 0) {
      let dataCheliangList = dataCheliang.data.row;
      let carArray = [], carRowId = [], sijiCarList = [];
      for (let value of dataCheliangList) {
        carArray.push(value.chelianghaoma);
        carRowId.push(value.row_id);
        if (value['jianzhisijisiji1;row_id'] && value['jianzhisijisiji1;value']) {
          sijiCarList.push(value) // 存储带有司机的车牌号
        }
      };
      this.setData({ carArray, carRowId, initDataCar: carArray, sijiCarList })
    } else {
      wx.$toast('车牌号码数据为空!')
    }
  },
  // 图片逻辑 =================================================================
  uploadImg () {
    this.comeLocation()
  },
  // 获取当前经纬度 换取中文地址
  comeLocation () {
    let that = this
    wx.$comeLocation((res) => {
      if (res.latitude && res.longitude) {
        that.setData({
          location: [res.latitude, res.longitude]
        }, () => {
          wx.$getLocationAdd(`${res.latitude},${res.longitude}`, (data) => {
            that.setData({
              locationName: data.result.address
            }, () => {
              that.comeImage()
            })
          })
        })
      }
    })
  },
  // 打拍照添加水印信息
  comeImage () {
    let that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      camera: ['back'],
      success (res) {
        const tempFilePaths = res.tempFiles
        if (tempFilePaths.length > 0) {
          that.setData({
            imageShow: tempFilePaths[0].tempFilePath
          }, () => {
            wx.showLoading({ title: '', })
            that.addWaterMark(tempFilePaths[0].tempFilePath).then(res => {
              that.setData({
                showImage: res.tempFilePath
              })
            })
          })
        }
      }
    })
  },
  addWaterMark (tempFilePath) {
    return new Promise((resolve, reject) => {
      let that = this
      wx.createSelectorQuery().select('#mycanvas').fields({
        node: true,
        size: true
      }).exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const imageSrc = tempFilePath;
        const times = wx.$util.formatTime(new Date());
        wx.getImageInfo({
          src: imageSrc,
          success: function (imageRes) {
            wx.showLoading({ title: '', })
            canvas.width = imageRes.width;
            canvas.height = imageRes.height;
            that.setData({
              canvasStyle: `width: ${imageRes.width}rpx;height: ${imageRes.height}rpx;position: fixed;left:9000px`
            })
            const image = canvas.createImage()
            image.onload = () => {
              ctx.drawImage(image, 0, 0, imageRes.width, imageRes.height)
              ctx.font = '30px Arial';
              ctx.fillStyle = 'red';
              ctx.strokeStyle = "black";
              let filltextHeight = imageRes.height - (that.drawText(ctx, that.data.locationName, imageRes.width, imageRes.height - 35, 232, 750 / 5 * 5) * 35);
              ctx.fillText(times, imageRes.width - (ctx.measureText(times).width + 30), filltextHeight);
              setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvas: canvas,
                  success: function (res) {
                    wx.hideLoading()
                    resolve(res)
                  },
                  fail: function (res) {
                    wx.hideLoading()
                    reject(res)
                    console.error(res);
                  }
                });
              }, 1000);
            }
            image.src = imageSrc
          }
        });
      });
    })
  },
  // 绘画字体 判断是否文字过多分行
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0;
    var heightLineNum = 0;
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        heightLineNum++;
        var title = str.substring(lastSubStrIndex, i);
        var leftWidthNum = leftWidth - ctx.measureText(title).width - 30;
        ctx.fillText(title, leftWidthNum, initHeight);
        initHeight -= 30;
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) {
        var title = str.substring(lastSubStrIndex, i + 1);
        var leftWidthNum = leftWidth - ctx.measureText(title).width - 30
        heightLineNum++;
        ctx.fillText(title, leftWidthNum, initHeight);
      }
    }
    titleHeight = titleHeight + 10;
    return heightLineNum + 1
  },
  previewIshowImg () {
    let that = this
    if (this.data.showImage != '') {
      wx.previewImage({
        urls: [that.data.showImage],
      })
    }
  },
  autograph () {
    let that = this;
    wx.navigateTo({
      url: '/repairPages/service_autograph/service_autograph',
      events: {
        getBindingImage: function (data) {
          that.setData({
            autographImage: data.showImg
          })
        },
      },
      success: function (res) {
        res.eventChannel.emit('service_Goin', { service_Goin: true })
      }
    })
  },
  serviceGoIsok () {
    this.uploadImageFile()
  },
  handleSearch (e) {
    let searchValue = e.detail;
    if (searchValue.trim() === '') {
      // 判断点击的是司机还是车牌
      if (this.data.showPickerCode == 'driver') {
        this.setData({ driverArray: this.data.initDatadriver })
      } else {
        this.setData({ carArray: this.data.initDataCar })

      }
    } else {
      let filteredList = [];
      if (this.data.showPickerCode == 'driver') {
        filteredList = this.data.initDatadriver.filter(item => {
          const selectName = item.toLowerCase().includes(searchValue);
          return selectName
        })
        this.setData({ driverArray: filteredList })
      } else {
        filteredList = this.data.initDataCar.filter(item => {
          const selectName = item.toLowerCase().includes(searchValue);
          return selectName
        })
        this.setData({ carArray: filteredList })
      }

    }
  },
  // 弹窗确认
  confirm (e) {
    if (e.detail && e.detail.selectIndex >= 0) { // 初始化为0 第一条数据
      let confirmIndex = e.detail.selectIndex;
      if (this.data.showPickerCode == 'driver') {
        this.setData({
          selectDatadriver: this.data.driverRowId[this.data.initDatadriver.indexOf(e.detail.name)],
          driver: this.data.driverArray[confirmIndex],
          showPickerIsok: !this.data.showPickerIsok,
          driverArray: this.data.initDatadriver // 重新初始化打开的数据
        })
      } else {
        let valueCar = {};
        for (let value of this.data.sijiCarList) {
          if (value.chelianghaoma == e.detail.name) {
            valueCar = value;
          }
        };
        // 判断是否有绑定司机
        if (Object.keys(valueCar).length > 0) {
          this.setData({
            selectDataCar: this.data.carRowId[this.data.initDataCar.indexOf(e.detail.name)],
            carTxt: this.data.carArray[confirmIndex],
            showPickerIsok: !this.data.showPickerIsok,
            carArray: this.data.initDataCar, // 重新初始化打开的数据
            driver: valueCar['jianzhisijisiji1;value'],
            selectDatadriver: valueCar['jianzhisijisiji1;row_id'],
          })
          return
        }
        this.setData({
          selectDataCar: this.data.carRowId[this.data.initDataCar.indexOf(e.detail.name)],
          carTxt: this.data.carArray[confirmIndex],
          showPickerIsok: !this.data.showPickerIsok,
          carArray: this.data.initDataCar, // 重新初始化打开的数据
        })
      }
    }
  },
  // 弹窗取消
  hiddPicker () {
    // 触发关闭 重新初始化打开的数据
    this.setData({
      showPickerIsok: !this.data.showPickerIsok,
      driverArray: this.data.initDatadriver,
      carArray: this.data.initDataCar
    })
  },
  showPicker (e) {
    if (e.currentTarget.dataset.datacode || e.target.dataset.datacode) {
      let code = e.currentTarget.dataset.datacode || e.target.dataset.datacode;
      this.setData({
        showPickerIsok: false,
        showPickerCode: code,
        placeholder: code == 'car' ? '请输入车牌号码进行查询' : '请输入司机名称进行查询',
      })
    }
  },
  showautographImg () {
    let that = this
    if (that.data.autographImage != '') {
      wx.previewImage({
        urls: [that.data.autographImage],
      })
    }
  },
  editValue (e) {
    let that = this;
    that.data[e.target.dataset.datacode] = e.detail;
  },
  async uploadImageFile () {
    let that = this, chooseImageData = null;
    if (that.data.selectDataCar == '' || !that.data.selectDataCar) {
      return wx.$toast('请选择车牌号码！')
    }
    if (this.data.selectDatadriver == '' || !this.data.selectDatadriver) {
      return wx.$toast('请选择司机姓名！')
    }
    // if (that.data.showImage == null || !that.data.showImage || that.data.showImage == '') {
    //   return wx.$toast('尚未拍照进场图片！')
    // }
    if (that.data.autographImage == null || !that.data.autographImage || that.data.autographImage == '') {
      return wx.$toast('尚未操作进场签名！')
    }
    wx.showLoading({ title: '正在提交资料，请稍后', })
    if (that.data.showImage) {
      chooseImageData = await wx.$uploadReq(that.data.showImage) // 上传进场拍照图片
    }
    let autographImageData = await wx.$uploadReq(that.data.autographImage) // 上传签名图片
    let request = {
      driver_id: that.data.selectDatadriver,
      car_id: that.data.selectDataCar,
      picture: '', //进场图片
      sign_pic: '',// 进场签名
      baoxiuxiangmu: that.data.baoxiuxiangmu, // 报修改项目
    }
    // 上传拍照图片结果处理
    if (chooseImageData != null) {
      if (chooseImageData.response.errcode != 0) return wx.$toast(res.response.errmsg)
      if (chooseImageData.data.row && chooseImageData.data.row.length > 0) {
        request.picture = chooseImageData.data.row[0].data
      } else {
        return wx.$toast('上传进场图片失败,请重新再试')
      }
    }
    // 上传签名图片结果处理
    if (autographImageData.response.errcode != 0) return wx.$toast(res.response.errmsg)
    if (autographImageData.data.row && autographImageData.data.row.length > 0) {
      request.sign_pic = autographImageData.data.row[0].data
    } else {
      return wx.$toast('上传进场图片失败,请重新再试')
    }
    wx.$post(5, 'BC/EntryMaintenance', request).then(res => {
      wx.hideLoading()
      if (res.response.errcode != 0) return wx.$toast(res.response.errmsg);
      wx.$toast('提交成功,已确认入场!', 1500).then(() => {
        that.initData();
      })
    })
  }
})
